package com.unswift.window.editor;

import java.util.HashMap;
import java.util.Map;

import javax.swing.JTextPane;

import com.unswift.window.component.UiComponent;
import com.unswift.window.factory.EditorFactory;
import com.unswift.window.listener.EditorKeyListener;
import com.unswift.window.listener.EditorMouseListener;
import com.unswift.window.undo.UndoManager;

@SuppressWarnings("serial")
public class Editor extends JTextPane implements UiComponent{
	
	private Map<String, Object> attribute;//存储表格关联的对象，见ATTRIBUTE_开头的常量
	private String busAction;//表格动作，什么类型的表格

	public Editor(String busAction, EditorDocument document, boolean editable) {
		super(document);
		this.busAction=busAction;
		this.attribute=new HashMap<String, Object>();
		EditorFactory.setTabWidth(this);//规定Tab键的宽度
		this.setEditable(editable);
		if(!editable){//如果不能编辑，还是可以获取焦点
			this.setFocusable(true);
			this.setRequestFocusEnabled(true);
		}
		this.setAttribute(ATTRIBUTE_EDITOR_UNDO_MANAGER, new UndoManager(document));
		document.setEditor(this);
		if(ACTION_AUTOMATION_JSON.equals(busAction) || ACTION_AUTOMATION_CONSOLE.equals(busAction) 
				|| ACTION_INTERFACE_JSON.equals(busAction) || ACTION_CREATE_INTERFACE_JSON.equals(busAction)
				|| ACTION_INTERFACE_CONSOLE.equals(busAction)){
			document.setPushUndo(true);
		}else{
			document.setPushUndo(false);
		}
		this.addKeyListener(new EditorKeyListener(this));
		this.addMouseListener(new EditorMouseListener(this));
	}
	
	@Override
	public void setText(String text) {
		super.setText(text);
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public <T> T getAttribute(String key) {
		return (T)attribute.get(key);
	}
	@Override
	public <T> void setAttribute(String key, T value) {
		this.attribute.put(key, value);
	}
	@Override
	public boolean existsAttribute(String key) {
		return attribute.containsKey(key);
	}
	@Override
	public void removeAttribute(String key) {
		this.attribute.remove(key);
	}
	@Override
	public String getBusAction() {
		return busAction;
	}
	@Override
	public void setBusAction(String busAction) {
		this.busAction = busAction;
	}
}
